package com.qiantu.phone.ui.activity;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.umeng.UmengClient;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.HouseBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.bean.TimeLimitBean;
import com.qiantu.phone.event.RoomIconSelectEvent;
import com.qiantu.phone.ui.dialog.BottomFloorDialog;
import com.qiantu.phone.ui.dialog.BottomTimeLimitDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.fragment.RoomIconFragment;
import com.qiantu.phone.ui.fragment.RoomListFragment;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.bean.LocationData;
import com.qiantu.phone.manager.FlowLayoutManager;
import com.qiantu.phone.ui.activity.map.LocationActivity;
import com.qiantu.phone.ui.adapter.RoomLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.lxj.xpopup.XPopup;
import com.qiantu.phone.widget.ViewPagerScrollIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class FamilyInfoActivity extends AppActivity {

    int type;//0.开启智家 1.添加房屋

    @Log
    public static void start(Context context) {
        Intent intent = new Intent(context, FamilyInfoActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void start(Context context, int type) {
        Intent intent = new Intent(context, FamilyInfoActivity.class);
        intent.putExtra("TYPE", type);
        context.startActivity(intent);
    }

    private SettingBar mName;
    private SettingBar mLocation;
    private SettingBar houseFloor;
    private TextView floorHints;
    private ViewPagerScrollIndicator tabBar;
    private int floorNum = 0;
    private View btnStart;
    private BottomEditDialog mBottomEditDialog;
    private LocationData locationData;
    private ArrayList<Map<String,Object>> floors;
    private List<String> floorTitles = new ArrayList<>();
    private static String floorNames[] = {"一楼", "二楼", "三楼", "四楼", "五楼", "六楼", "七楼", "八楼"};
    private BottomFloorDialog mBottomFloorDialog;
    private List<Fragment> fragments = new ArrayList<>();

    FragmentPagerAdapter<Fragment> mPagerAdapter;
    private ViewPager viewPager;

    @Override
    protected int getLayoutId() {
        return R.layout.family_info_activity;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        EventBus.getDefault().register(this);
        type = getIntent().getIntExtra("TYPE", 0);
        floors = new ArrayList<>();
        mName = findViewById(R.id.name);
        mLocation = findViewById(R.id.location);
        houseFloor = findViewById(R.id.house_floor);
        houseFloor.setRightText(floorNum + "");
        tabBar = findViewById(R.id.tab_bar);
        floorHints = findViewById(R.id.add_house_hints);
        viewPager = findViewById(R.id.view_pager);
        TextView btnSkip = findViewById(R.id.btn_skip);
        btnStart = findViewById(R.id.btn_start);
        setOnClickListener(R.id.name, R.id.location, R.id.house_floor, R.id.btn_skip, R.id.btn_start);
        btnSkip.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        btnSkip.getPaint().setAntiAlias(true);//抗锯齿
        if (type == 1){
            setTitle(R.string.add_house);
            btnSkip.setVisibility(View.INVISIBLE);
            TextView textView = findViewById(R.id.btn_start);
            textView.setText(R.string.save);
            btnSkip.setVisibility(View.GONE);
            mName.setRightText(null);
        }else{
//            getTitleBar().setLeftIcon(null);
        }
    }

    private void setBtnEnable(){
//        if(!TextUtils.isEmpty(mName.getRightText()) && !TextUtils.isEmpty(mLocation.getRightText())){
        if(!TextUtils.isEmpty(mName.getRightText())){
            btnStart.setEnabled(true);
        }else{
            btnStart.setEnabled(false);
        }
    }

    @Override
    public void onBackPressed() {
        //开启智家时，整个app就当前页面，返回做回到桌面处理
        if(type == 0){
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        }else{
            super.onBackPressed();
        }
    }

    @Override
    protected void initData() {
        boolean isFirst = fragments.size() == 0;
        List<Fragment> oldFragments = new ArrayList<>();
        for(Fragment fragment : fragments){
            oldFragments.add(fragment);
        }
        fragments.clear();
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        fragments = new ArrayList<>();
        floorTitles.clear();
        int num = 1;
        if(floorNum == 0){
            tabBar.setVisibility(View.GONE);
        }else{
            num = floorNum;
            tabBar.setVisibility(View.VISIBLE);
        }
        for(int i = floors.size(); i > num;i--){
            if(i == 1 && num == 0){
                break;
            }else{
                floors.remove(i - 1);
            }
        }
        for (int i = 0; i < num; i++) {
            RoomIconFragment fragment;
            if(floors.size() > i){
                fragment = (RoomIconFragment) oldFragments.get(i);
                fragment.setSelectData((List<String>) floors.get(i).get("roomTypes"));
            }else{
                fragment = RoomIconFragment.newInstance(false, false,"");
                Map<String,Object> map = new HashMap<>();
                List<String> list = new ArrayList<>();
                map.put("name",floorNames[i]);
                map.put("roomTypes",list);
                floors.add(map);
            }
            floorTitles.add(floorNames[i]);
            fragments.add(fragment);
            mPagerAdapter.addFragment(fragment);
        }
        viewPager.setAdapter(mPagerAdapter);
        tabBar.setupViewpager(viewPager);
        tabBar.setTitleList(floorTitles);
        if(tabBar.getCurrentItem() > floorTitles.size()){
            tabBar.selectTab(floorTitles.size() - 1);
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.name:
                showBottomEditDialog(mName.getRightText().toString());
                break;
            case R.id.location:
                String[] needPermissions = {
                        ACCESS_COARSE_LOCATION,
                        ACCESS_FINE_LOCATION,
                };
                if(!XXPermissions.isGranted(getContext(),needPermissions) && AppApplication.isHuawei() ){
                    showConfirmHintDialog("App需要使用您的位置权限，来设定你的房屋位置，通过你的房屋位置来获取当地天气进行联动等功能的实现。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的位置权限改为允许。");
                }else{
                    LocationActivity.startForResult(this, null, LocationActivity.LOCATION_REQUEST_CODE);
                }
                break;
            case R.id.house_floor:
                showBottomFloorDialog();
                break;
            case R.id.btn_skip:
                //跳过也注册结束
                AppApplication.getInstance().getLoginInfo().setRegistrationProgress(3);
                AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
//                HomeActivity.start(this);
                AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.init_house_info));
                break;
            case R.id.btn_start:
                start();
                break;
        }
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    mName.setRightText(mBottomEditDialog.getText());
//                    btnStart.setEnabled(!TextUtils.isEmpty(tvFamilyName.getText()));
                    setBtnEnable();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.house_home));
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.HOUSE_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void showBottomFloorDialog() {
        if (mBottomFloorDialog == null) {
            mBottomFloorDialog = new BottomFloorDialog(getContext());
            mBottomFloorDialog.setLabel("楼层数量");
            mBottomFloorDialog.setDialogClickListener(new BottomFloorDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int num) {
                    mBottomFloorDialog.dismiss();
                    floorNum = num;
                    if(floorNum == 0){
                        floorHints.setText("添加房间");
                    }else{
                        floorHints.setText("为楼层添加房间");
                    }
                    houseFloor.setRightText(num + "");
                    initData();
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomFloorDialog);
        }
        mBottomFloorDialog.setSelectedItem(floorNum);
        mBottomFloorDialog.show();
    }

    private void start() {
        String houseName = mName.getRightText() == null ? null : mName.getRightText().toString().trim();
        if (TextUtils.isEmpty(houseName)) {
            toast(R.string.please_enter_house_name);
            return;
        }
        String houseLocation = mLocation.getRightText() == null ? null : mLocation.getRightText().toString();
//        if (TextUtils.isEmpty(houseLocation)) {
//            toast(R.string.please_select_location);
//            return;
//        }
//        List<String> selectedRooms = mRoomLabelAdapter.getSelectedData();
//        if (selectedRooms == null || selectedRooms.size() == 0) {
//            toast(R.string.please_select_room);
//            return;
//        }

        // 隐藏软键盘
        hideKeyboard(getCurrentFocus());
        Map<String, Object> data = new HashMap<>();
        data.put("name", houseName);
        data.put("avatar", "");
        // 添加默认值逻辑
        if (locationData == null) {
            locationData = new LocationData();
            locationData.longitude = 0;
            locationData.latitude = 0;
            locationData.provinceId = "";
            locationData.province = "";
            locationData.city = "";
            locationData.district = "";
            locationData.districtId = "";
        }
        if (TextUtils.isEmpty(houseLocation)) {
            houseLocation = "";
        }

        data.put("longitude", locationData.longitude);
        data.put("latitude", locationData.latitude);
        data.put("provinceId", 0);
        data.put("province", locationData.province);
        data.put("city", locationData.city);
        data.put("district", locationData.district);
        data.put("districtId", 0);
        data.put("address", houseLocation);
        data.put("isFlatFloor", true);
        data.put("type", type);
        if(floorNum == 0){
            data.put("roomTypeList",floors.get(0).get("roomTypes"));
            LLHttpManager.addHouse(this, data, new HttpCallback<HttpData<HouseBean>>(this){

                @Override
                public void onStart(Call call) {
                    showDialog(getString(R.string.creating_house));
                }

                @Override
                public void onSucceed(HttpData<HouseBean> result) {
                    super.onSucceed(result);
                    toast(R.string.create_success);
                    //更新注册进度
                    AppApplication.getInstance().getLoginInfo().setRegistrationProgress(3);
                    AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
                    HouseBean house = result.getData();
                    if(type == 0){
                        AppApplication.getInstance().setCurHouseInfo(house);
                        AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.init_house_info));
                    }else{
//                    setResult(RESULT_OK);
//                    finish();
                        String loginToken = null;
                        if(AppApplication.getInstance().getLoginInfo() != null){
                            loginToken = AppApplication.getInstance().getLoginInfo().getToken();
                        }
                        LLHttpManager.editDefaultHouse(FamilyInfoActivity.this, loginToken, house.getHouseSerialNo(), new HttpCallback<HttpData<Void>>(FamilyInfoActivity.this) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(getString(R.string.switching_houses));
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                AppApplication.getInstance().setCurHouseInfo(house);
                                AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.switching_houses));
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }

                            @Override
                            public void onEnd(Call call) {
                                hideDialog();
                            }
                        });
                    }
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    super.onEnd(call);
                }
            });
        }else{
            data.put("floorList",floors);
            LLHttpManager.addHouseWithFloor(this, data, new HttpCallback<HttpData<HouseBean>>(this){

                @Override
                public void onStart(Call call) {
                    showDialog(getString(R.string.creating_house));
                }

                @Override
                public void onSucceed(HttpData<HouseBean> result) {
                    super.onSucceed(result);
                    toast(R.string.create_success);
                    //更新注册进度
                    AppApplication.getInstance().getLoginInfo().setRegistrationProgress(3);
                    AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
                    HouseBean house = result.getData();
                    if(type == 0){
                        AppApplication.getInstance().setCurHouseInfo(house);
                        AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.init_house_info));
                    }else{
//                    setResult(RESULT_OK);
//                    finish();
                        String loginToken = null;
                        if(AppApplication.getInstance().getLoginInfo() != null){
                            loginToken = AppApplication.getInstance().getLoginInfo().getToken();
                        }
                        LLHttpManager.editDefaultHouse(FamilyInfoActivity.this, loginToken, house.getHouseSerialNo(), new HttpCallback<HttpData<Void>>(FamilyInfoActivity.this) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(getString(R.string.switching_houses));
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                AppApplication.getInstance().setCurHouseInfo(house);
                                AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.switching_houses));
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }

                            @Override
                            public void onEnd(Call call) {
                                hideDialog();
                            }
                        });
                    }
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    super.onEnd(call);
                }
            });
        }

    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            gotoLocation();
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void gotoLocation(){
        LocationActivity.startForResult(this, null, LocationActivity.LOCATION_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
        if(resultCode != RESULT_OK){
            return;
        }
        switch (requestCode){
            case LocationActivity.LOCATION_REQUEST_CODE:
                locationData = (LocationData) data.getSerializableExtra("DATA");
                if(locationData != null){
                    mLocation.setRightText(locationData.city + locationData.locationCN);
                }
//                btnStart.setEnabled(!TextUtils.isEmpty(tvFamilyLocation.getText()));
                setBtnEnable();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRoomIconSelectEvent(RoomIconSelectEvent event) {
        ArrayList<Map> selectData = event.selectData;
        ArrayList<String> types = new ArrayList<>();
        for (Map map : selectData) {
            types.add(map.get("type").toString());
        }
        floors.get(tabBar.getCurrentItem()).put("roomTypes",types);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}